<template>
  <!--<div class="login-container">-->
  <div style="min-width: 1100px">
    <div class="licc-consumer-top">
      <el-form :model="filterConditions" ref="filterConditions"  label-width="80px">
        <el-row>
          <el-col :span="6">
            <el-form-item
              label="账号"
              prop="loginName"
              :rules="[{trigger: 'blur', validator: validateloginNameRule}]">
              <el-input v-model="filterConditions.loginName" placeholder="请输入账号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label=添加时间>
              <el-date-picker
                v-model="datePickerValue"
                value-format="yyyy-MM-dd HH:mm:SS"
                :picker-options="pickerOptions"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="4">
            <el-button type="info" @click="restUserInfosButton">重 置</el-button>
            <el-button type="primary" @click="selectUserInfosButton">筛 选</el-button>
            <el-button type="primary" @click="adminInfoAdd">添 加</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div>
      <el-table
        stripe
        border
        :data="admins"
        :default-sort = "{prop: 'createDate', order: 'descending'}">
        <el-table-column
          type="index">
        </el-table-column>
        <el-table-column prop="loginName" label="账号名" sortable></el-table-column>
        <el-table-column prop="nickname" label="真名" ></el-table-column>
        <el-table-column prop="createDate" label="添加时间" sortable></el-table-column>
        <el-table-column prop="phone" label="联系电话" sortable></el-table-column>
        <el-table-column prop="email" label="身份证号" sortable></el-table-column>
        <el-table-column prop="disabled" label="可登录">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.disabled"
              @change="userSwitchChange(scope.row)"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="250">
          <template slot-scope="scope">
            <el-button @click="deleteClick(scope.row)" type="danger" size="mini">删除</el-button>
            <el-button @click="handleClick(scope.row)" type="primary" size="mini">编辑</el-button>
            <el-button @click="restPasswordClick(scope.row)" type="warning" size="mini">密码重置</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 35, 50]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="goodsTotal">
      </el-pagination>
    </div>
    <div>
      <el-dialog
        title="添加账户信息"
        :visible.sync="adminDialogVisible"
        width="900px"
        :before-close="handleClose">
        <span>
          <el-form :model="addAdminInfo" :rules="addAdminInfoRules" ref="addAdminInfo" label-width="100px">
            <el-row>
              <el-col :span="10">
                <el-form-item
                  label="账号"
                  prop="loginName">
                  <el-input name="loginName" v-model="addAdminInfo.loginName" placeholder="输入账号"></el-input>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item
                  label="姓名"
                  prop="nickname">
                  <el-input name="nickname" v-model="addAdminInfo.nickname" placeholder="输入真实姓名"></el-input>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="10">
                <el-form-item
                  label="手机号"
                  prop="phone">
                  <el-input name="phone" v-model="addAdminInfo.phone" placeholder="输入手机号码"></el-input>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item
                  label="身份证号"
                  prop="email">
                  <el-input name="email" v-model="addAdminInfo.email" placeholder="输入身份证号"></el-input>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </span>
        <span slot="footer" class="dialog-footer">
        <el-button @click="adminDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="adminInfoSave">保 存</el-button>
      </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import userApi from '@/api/backstage/user'

  export default {
    name: 'Goods_listInfo',
    data() {
      const validateLoginName = (rule, value, callback) => {
        if (value === ''||typeof(value)=="undefined") {
          callback(new Error('请输入账号'));
        }
        let loginNameRule = /^[a-zA-Z0-9_][a-zA-Z0-9_]{4,15}$/
        if (!loginNameRule.test(value)){
          callback(new Error('由5-16字符下划线、数字或字母组成'));
        }
        callback();
      }
      const validateNickname = (rule, value, callback) => {
        if (value === ''||typeof(value)=="undefined") {
          callback(new Error('请输入真实姓名'));
        }
        let nicknameRule = /^[\u4E00-\u9FA5]+(·[\u4E00-\u9FA5]+)*$/
        if (!nicknameRule.test(value)){
          callback(new Error('汉字或“汉字·汉字”的形式组成'));
        }
        callback();
      }
      const validatePhone = (rule, value, callback) => {
        if (value === ''||typeof(value)=="undefined") {
          callback(new Error('请输入手机号'));
        }
        let phoneRule = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/
        if (!phoneRule.test(value)){
          callback(new Error('请输入正确的手机号格式'));
        }
        callback();
      }
      const validateEmail = (rule, value, callback) => {
        if (value === ''||typeof(value)=="undefined") {
          callback(new Error('请输入身份证号'));
        }
        let emailRule = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$)/
        if (!emailRule.test(value)){
          callback(new Error('请输入正确的身份证号'));
        }
        callback();
      }
      return {
        roleId:'dac6ecb92c004716b1767fcc93b61489',
        admins:[],
        currentPage: 1,
        pagesize:20,
        goodsTotal:0,
        /** 筛选条件 **/
        filterConditions:{},
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now() - 8.64e6
          }
        },
        /** 待匹配号码 **/
        // loginName: '',
        /** 日期选择器 **/
        datePickerValue:'',
        paramsInfo:{roleId:"dac6ecb92c004716b1767fcc93b61489"},
        /** 添加信息弹框不显示 **/
        adminDialogVisible: false,
        /** 添加账号信息Form **/
        addAdminInfo:{},
        addAdminInfoRules: {
          loginName: [{required: true, trigger: 'blur', validator: validateLoginName}],
          nickname: [{required: true, trigger: 'blur', validator: validateNickname}],
          phone: [{required: true, trigger: 'blur', validator: validatePhone}],
          email: [{required: true, trigger: 'blur', validator: validateEmail}],
        },
      }
    },
    created() {
      this.initData({roleId:this.roleId})
    },
    methods:{
      initData(params){
        userApi.getAdminInfo(params, this.currentPage, this.pagesize).then(res => {
          this.admins = res.data.records;
          this.goodsTotal = res.data.total;
        }).catch(() => {
          this.$notify.error({title: '失败', message: "获取用户信息失败"});
        })
      },
      userSwitchChange(row){
        /** 禁用或启用用户信息 **/
        let content = (row.disabled === 1)?'该操作将会解封“'+row.loginName+'”账号，是否继续？':'该操作将会冻结“'+row.loginName+'”账号，是否继续？';
        this.$confirm(content, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let params = {
            id:row.id,
            disabled:row.disabled
          }
          userApi.updateAdminInfo(params).then(res => {
            this.$notify({title: '成功', message: "修改账号状态成功", type: 'success'});
          }).catch(() => {
            this.$notify.error({title: '失败', message: "账号状态修改失败"});
            row.disabled = (row.disabled === 1)?0:1;
          })
        }).catch(() => {
          /** 取消提交 **/
          row.disabled = (row.disabled === 1)?0:1;
          this.$notify.info({title: '取消', message: '已取消提交操作'});
        });
      },
      /** 分页---开始 **/
      handleSizeChange(val) {
        this.pagesize = val;
        this.initData(this.paramsInfo);
        console.log(`每页 ${val} 条`);
      },
      handleCurrentChange(val) {
        this.currentPage = val;
        this.initData(this.paramsInfo);
        console.log(`当前页: ${val}`);
      },
      /** 分页---结束 **/
      /** 搜索规则--开始 **/
      validateloginNameRule(rule, value, callback){
        let loginNameRule = /^[a-zA-Z0-9_][a-zA-Z0-9_]{2,15}$/;
        if (!loginNameRule.test(value)) {
          callback(new Error('由3-16字符下划线、数字或字母组成'))
        } else {
          callback()
        }
      },
      /** 搜索规则--结束 **/
      selectUserInfosButton(){
        if((this.filterConditions.loginName===''||this.filterConditions.loginName==null||typeof(this.filterConditions.loginName)=="undefined")&&(this.datePickerValue === ''||this.datePickerValue==null)){
          this.$notify({title: '提示', message: '请输入筛选信息', type: 'warning'});
          return false;
        }
        this.paramsInfo = {};
        this.paramsInfo = (this.filterConditions.loginName === '')?{}:{loginName:this.filterConditions.loginName};
        this.paramsInfo.roleId = this.roleId
        if (this.datePickerValue !== ''&&this.datePickerValue!=null){
          this.paramsInfo.date = this.datePickerValue[0]+","+this.datePickerValue[1];
        }
        this.$refs['filterConditions'].validate(valid => {
          if (valid){
            this.initData(this.paramsInfo);
          } else {
            this.$notify({title: '提示', message: '输入的账号信息不合规', type: 'warning'});
          }
        });
      },
      /** 重置搜索--结束 **/
      restUserInfosButton(){
        this.filterConditions.loginName = '';
        this.datePickerValue = null;
        this.paramsInfo = {};
        this.paramsInfo.roleId = this.roleId
        this.$refs['filterConditions'].clearValidate();
        this.initData(this.paramsInfo);
      },
      /** 添加 **/
      adminInfoAdd(){
        this.addAdminInfo = {};
        this.$nextTick(()=>{
          this.$refs['addAdminInfo'].clearValidate();
        })
        this.adminDialogVisible = true;
      },
      /** 删除按钮事件 **/
      deleteClick(row){
        this.$confirm('此操作将永久删除“'+row.loginName+'”账号, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          userApi.deleteAdminInfo({id: row.id, remarks: this.roleId}).then(res => {
            this.initData(this.paramsInfo);
            this.$notify({title: '成功', message: "删除成功", type: 'success'});
          }).catch(() => {
            this.$notify.error({title: '失败', message: "删除失败"});
          });
        }).catch(() => {
          this.$notify.info({title: '取消', message: "取消删除操作"});
        });
      },
      /** 编辑按钮事件 **/
      handleClick(row){
        this.addAdminInfo = {};
        this.$nextTick(()=>{
          this.$refs['addAdminInfo'].clearValidate();
        })
        this.addAdminInfo = row;
        this.adminDialogVisible = true;
      },
      /** 密码重置事件 **/
      restPasswordClick(row){
        this.$confirm('此操作将重置“'+row.loginName+'”账号密码, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          userApi.souAdminInfo({id: row.id}).then(res => {
            this.initData(this.paramsInfo);
            this.$notify({title: '成功', message: "重置密码成功", type: 'success'});
          }).catch(() => {
            this.$notify.error({title: '失败', message: "重置密码失败"});
          });
        }).catch(() => {
          this.$notify.info({title: '取消', message: "取消重置密码操作"});
        });
      },
      /** 关闭添加添加弹出框 **/
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      /** 管理员信息保存事件 **/
      adminInfoSave(){
        this.$refs['addAdminInfo'].validate(valid => {
          if (valid){
            /** 上传角色信息 **/
            this.addAdminInfo.remarks = this.roleId;
            userApi.souAdminInfo(this.addAdminInfo).then(res => {
              this.adminDialogVisible = false;
              this.initData(this.paramsInfo);
              this.$notify({title: '成功', message: "操作成功", type: 'success'});
            }).catch(() => {
              this.$notify.error({title: '失败', message: "操作失败"});
            });
          } else {
            this.$notify({title: '提示', message: '输入的信息中有不合规', type: 'warning'});
          }
        });
      }
    }
  }
</script>
<style>
  .licc-consumer-top{
    width: 100%;
    min-width: 1100px;
  }
</style>
